package cn.itsource.service;

import cn.itsource.config.TxCosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.InputStream;

/**
 * @program fccar_240420
 * @Description
 * @Date 2024/09/12 16:30
 * @Version 1.0
 */
public class TXCosTemplate {
    //https://fccar-1304156448.cos.ap-nanjing.myqcloud.com/driver/c032bed9-8967-4db7-af8b-afad4e5e1f9b.png
    private static final String COS_URL =  "https://%s.cos.%s.myqcloud.com/%s";
    private TxCosConfig txCosConfig;

    public TXCosTemplate(TxCosConfig txCosConfig) {
        this.txCosConfig = txCosConfig;
    }

    public String upload(InputStream file, String fileName){
        String secretId = txCosConfig.getSecretId();//用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        String secretKey = txCosConfig.getSecretKey();//用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(txCosConfig.getRegionName());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        fileName = txCosConfig.getFolder()+fileName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(txCosConfig.getBucketName(), fileName, file,new ObjectMetadata());
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        //返回文件路径
        String path = String.format(COS_URL, txCosConfig.getBucketName(),txCosConfig.getRegionName(),fileName);
        cosClient.shutdown();
        return path;
    }
}
